﻿if (typeof Axis == "undefined") Axis = {};
if (typeof Axis.Admin == "undefined") Axis.Admin = {};
if (typeof Axis.Admin.Research == "undefined") Axis.Admin.Research = {};
Axis.Admin.Research.Question =
{
    IndexRow: 2,
    ResearchID: 0,
    GenarateOption: function (rows, value, text) {
        var cssClass = 'optAnswersCol';
        if (rows == 1)
            cssClass = 'optAnswersRow';
        var pattern = '<div class="new-row optDivAnswers"> <div class="wrap-control"> <div class="QuestionOpen">&nbsp;</div></div><input type="text" qValue="{0}" value="{1}" class="ui-widget-content ui-corner-all {2}"/>  </div>';
        if (rows == 2)
            $("#QuestionRow").append($.string.Format(pattern, value, text, cssClass));
        else
            $("#QuestionCol").append($.string.Format(pattern, value, text, cssClass));
    },
    DialogQuestion: {
        ID: "#FormQuestion",
        Dialog: null,
        Init: function (action, opts) {
            var thisObj = this;
            thisObj.ClearForm();
            Axis.Admin.Research.Question.ResearchID = opts.ID;
            Axis.Admin.Research.Question.LoadQuestion(opts.ID);
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Hiệu chỉnh câu hỏi khảo sát",
                    width: 450,
                    position: {
                        my: 'top',
                        at: 'top'
                    },
                    open: function () {

                    }
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
            var buttonText = "";

            var buttons = [
                        {
                            text: 'Hiệu chỉnh',
                            click: function (e) {
                                console.log(action, opts);
                                Axis.Admin.Research.Question.Update(action, opts);
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Cancel",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

            ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        },
        ClearForm: function () {
           $(".optAnswersCol,.optAnswersRow,.optDivAnswers").remove();

        }
    },
    LoadQuestion: function (ID) {
        var objThis = this;
 var pData = '{' + $.string.Format('"ProjectID":{0}', ID) + '}';
                $.ajax({
                    url: 'Service/ResearchQuestionService.asmx/GetQuestionDetail',
                    type: 'POST',
                    data: pData,
                    cache: false,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (pData, textStatus, jqXHR) {
                   
                        data = eval("(" + pData.d + ")");
                        if(data.QuesRow!=undefined){
                         if(data.QuesRow.length>0){
                         $("#txtCodeQuestion").val(data.QuesRow[0].Code);
                          $("#txtContent").val(data.QuesRow[0].QuestionText);
                         }
                            for(var i=1;i<data.QuesRow.length;i++)
                             objThis.GenarateOption(2, data.QuesRow[i].ID, data.QuesRow[i].QuestionText);
                        }
                        if(data.QuesCol!=undefined){
                            $.each(data.QuesCol,function(index,item){
                             objThis.GenarateOption(1, item.ID,item.Caption);

                            });
                       }
                       if(data.QuesCol.length==0)
                         objThis.GenarateOption(1, '', '');
                      if(data.QuesRow.length<2)
                         objThis.GenarateOption(2, '', '');


                    },
                    beforeSend: function (jqXHR, settings) {
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                    },
                    complete: function (XMLHttpRequest, textStatus) {
                    }
                });

    },
    Update: function () {
        var data = { Code: $("#txtCode").val(), QuestionText: $("#txtContent").val(), Type: 5, ProjectID: Axis.Admin.Research.Question.ResearchID ,DisplayRandomResponse:0};
        var pattern = "<ResponseOption Value='{0}'  Caption='Phương án sô {0}' Description='{1}' ZOrder='{0}'/>";
        var ret = "{ResponseOption:[";
        $.each($("input.optAnswersRow"), function (index, item) {
            var value = index + 1;
            var desc = $(item).val();
            var qValue = $(item).attr('qValue');
            var qType = 5;
            ret += "{";
            var AllowInputText = "0";
            if (typeof qType != 'undefined') {
                // if ($($.string.Format("input[id='AllowInput{0}']:checked", qValue)).length>0)
                //    
                if ($(item).prev().children(), $(item).prev().children().is(':checked'))
                    AllowInputText = "1";
            }
            if (data.ID != 0 && qValue != undefined)
                ret += $.string.Format('ID:"{0}",', 0);
            ret += $.string.Format('QuestionnaireID:"{0}",', "0");
            ret += $.string.Format('Value:"{0}",',value);
            ret += $.string.Format('Caption:"{0}",', $.HtmlEncode(desc));
            ret += $.string.Format('ZOrder:"{0}",', index);
            ret += $.string.Format('Description:"{0}"', $.HtmlEncode(desc));
            ret += "}";
            if (index != $("input.optAnswersRow").size() - 1) {
                ret += ",";
            }
        });
        ret += "],ColOption:[";
        $.each($("input.optAnswersCol"), function (index, item) {
            var value = index + 1;
            var desc = $(item).val();
            var qValue = $(item).attr('qValue');
            ret += "{";
            if (data.ID != 0 && qValue != undefined)
                ret += $.string.Format('ID:"{0}",', 0);
            ret += $.string.Format('QuestionnaireID:"{0}",', "0");
            ret += $.string.Format('Value:"{0}",',value);
            ret += $.string.Format('Caption:"{0}",',$.HtmlEncode( desc));
            ret += $.string.Format('ZOrder:"{0}",', index);
            ret += $.string.Format('Description:"{0}"', $.HtmlEncode(desc));
            ret += "}";
            if (index != $("input.optAnswersCol").size() - 1) {
                ret += ",";
            }
        });

        ret += "]}";
        data.Action = 'INSERT';
        data.DisplayRandomResponse=0;
        data.Code= data.CodeQuestion;
        data.ResponseOption = ret;
        if (typeof USER_ID != "undefined") {
            data.UserID = USER_ID;
            data.SecrectToken = SECRECT_TOKEN;
        }
        $.Ajax({
            url: 'Service/QuestionService.ashx',
            type: 'POST',
            data: data,
            success: function (data, textStatus, jqXHR) {
                if (data) {
                    data = eval("(" + data + ")");
                    if (data.IsSuccessfull) {
                          $.CAlert.Alert({
                    Title: "OK",
                    Content: "Câu hỏi đã được cập nhập",
                });
                    }
                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });

    }
}

$(function () {
    var objThis = Axis.Admin.Research.Question;
    $(".optAnswersRow").live('keydown', 'Return', function (evt) {
        objThis.GenarateOption(1, '', '');
        $(".optAnswersRow:last").focus();
        return false;
    }).live('keydown', 'DEL', function (evt) {
        $(this).parent().remove();
        return false;
    });

    $(".optAnswersCol").live('keydown', 'Return', function (evt) {
        objThis.GenarateOption(2, '', '');
        $(".optAnswersCol:last").focus();
        return false;
    }).live('keydown', 'DEL', function (evt) {
        $(this).parent().remove();
        return false;
    });

});